<template>
  <div class="market-price">
    <a-space class="button-group">
      <a-button type="primary" @click="getPirce" :loading="loading">
        获取价格
      </a-button>
      <a-button @click="autoCreate">一键制造</a-button>
    </a-space>

    <a-list v-if="outputText.length" bordered class="output-list">
      <a-list-item v-for="text in outputText" :key="text">
        {{ text }}
      </a-list-item>
    </a-list>

    <a-table
      :columns="columns"
      :data-source="formatTableData"
      :pagination="false"
      :rowClassName="(record) => record.hasLirun ? 'has-profit' : ''"
      class="price-table"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex.includes('city')">
          <div class="price-cell">
            <span :style="{ color: record[column.dataIndex].minPriceColor }">
              {{ record[column.dataIndex].isMinSellPrice ? '卖' : '' }}
              {{ record[column.dataIndex].sell_price_min }}
            </span>
            <span :style="{ color: record[column.dataIndex].maxPriceColor }">
              {{ record[column.dataIndex].isMaxBuyPrice ? '买' : '' }}
              {{ record[column.dataIndex].buy_price_max }}
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script>
import items from "./items/index";
import { getPrice } from "../request";
import { getCityName, getMakeLirun, getOutputInfo } from "../utils";
const currentData = items[0];
const cacheKey = "marketPrice";

export default {
  emits: ["search"],
  data() {
    return {
      loading: false,
      columns: [
        {
          title: 'Item',
          dataIndex: 'name',
          key: 'name',
          fixed: 'left',
          width: 160
        },
        ...['city1', 'city2', 'city3', 'city4', 'city5'].map(city => ({
          title: this.getCityName(city),
          dataIndex: `city_${city}`,
          key: city,
          width: 120
        }))
      ],
      tableData: [
        {
          id: "CLOTH",
          citys: [
            {
              id: "chengshi1",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi2",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengsh3",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi4",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi5",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
          ],
        },
      ],
      lastGetTime: "",
      refreshed: false,
      outputText: []
    };
  },
  computed: {
    formatTableData() {
      return this.tableData.map(item => {
        const formattedItem = {
          key: item.id,
          name: `${item.id.slice(0, 2)}${item.name || ''}`,
          hasLirun: item.hasLirun
        };
        
        item.citys.forEach((city, index) => {
          formattedItem[`city_city${index + 1}`] = city;
        });
        
        return formattedItem;
      });
    }
  },
  mounted() {
    const cacheData = localStorage.getItem(cacheKey);
    if (cacheData) {
      const _cacheData = JSON.parse(cacheData);
      this.complete(_cacheData);
    }
  },
  methods: {
    getCityName,
    autoCreate() {
      // if (!this.refreshed) {
      //   alert("请刷新数据");
      //   return;
      // }
      const result = getMakeLirun([...this.tableData], 2000, 0.04, 0.366);
      const outputText = [];
      result.forEach(item => {
        const outputInfo = getOutputInfo(item);
        outputText.push(outputInfo);
      })
      this.outputText = outputText;
    },
    complete(data) {
      const items = [];
      data.forEach((item) => {
        const id = item.item_id;
        const findIndex = items.findIndex((it) => it.id === id);
        if (findIndex > -1) {
          items[findIndex].citys.push(item);
        } else {
          items.push({
            id: id,
            citys: [item],
          });
        }
      });
      let newData = this.setColor(items);
      newData = this.setName(newData);
      console.log("newData: ", newData);
      this.tableData = newData;
    },
    setColor(data) {
      data.forEach((item) => {
        item.citys.forEach((city) => {
          const minPriceDate = city.buy_price_min_date;
          const minPriceColor = this.getColorByDate(new Date(minPriceDate));
          const maxPriceDate = city.sell_price_max_date;
          const maxPriceColor = this.getColorByDate(new Date(maxPriceDate));
          city.minPriceColor = minPriceColor;
          city.maxPriceColor = maxPriceColor;
        });
        let hasLirun = false;
        const minSellPrice = Math.min(
          ...item.citys.map((item) =>
            item.sell_price_min === 0 ? 999999999 : item.sell_price_min
          )
        );
        const maxBuyPrice = Math.max(
          ...item.citys.map((item) =>
            item.buy_price_max === 0 ? 0 : item.buy_price_max
          )
        );
        if (
          (maxBuyPrice - minSellPrice - maxBuyPrice * 0.04) * 1500 >
          1000 * 1000
        ) {
          hasLirun = true;
        }
        hasLirun &&
          item.citys.forEach((item) => {
            if (item.sell_price_min === minSellPrice) {
              item.isMinSellPrice = true;
            }
          });
        hasLirun &&
          item.citys.forEach((item) => {
            if (item.buy_price_max === maxBuyPrice) {
              item.isMaxBuyPrice = true;
            }
          });
        item.hasLirun = hasLirun;
      });
      return data;
    },
    // 根据id获取名称
    setName(newData) {
      newData.forEach((item) => {
        currentData.list.forEach((it) => {
          if (it.list && Array.isArray(it.list)) {
            const name = it.list.find((it) => it.id === item.id)?.name;
            if (name) {
              item.name = name;
            }
          }
        });
      });
      return newData;
    },
    // 根据时间获取颜色，离当前时间越近，颜色越深
    getColorByDate(date) {
      const now = new Date();
      let diff = (now.getTime() - date.getTime()) / 1000;
      diff = diff - 8 * 3600;
      if (diff < 3600) {
        return "#000";
      } else if (diff < 3 * 3600) {
        return "#333";
      } else if (diff < 7 * 3600) {
        return "#666";
      } else if (diff < 15 * 3600) {
        return "#999";
      } else {
        return "#ccc";
      }
    },
    async getPirce() {
      if (this.lastGetTime && new Date().getTime() - this.lastGetTime < 60 * 1000) {
        this.$message.warning('1分钟内只能获取一次');
        return;
      }
      
      this.loading = true;
      try {
        const idsList = [];
        currentData.list.forEach((item) => {
          const ids = item.list.map((li) => {
            return li.id;
          });
          idsList.push(...ids);
        });
        let orderList = idsList.sort();
        orderList = orderList.filter(
          (item) => item.indexOf("T7") === -1 && item.indexOf("T8") === -1
        );
        const { data } = await getPrice({
          item: orderList.join(","),
          hasRed: true,
        });
        this.refreshed = true;
        localStorage.setItem(cacheKey, JSON.stringify(data));
        this.complete(data);
      } catch (error) {
        this.$message.error('获取价格失败');
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style>
.market-price {
  padding: 24px;
  height: 90vh;
  overflow-y: auto;
}

.button-group {
  margin-bottom: 16px;
}

.output-list {
  margin-bottom: 16px;
}

.price-table {
  background: #fff;
}

.price-cell {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.has-profit {
  background-color: #fff1f0;
}

.has-profit td {
  border-color: #ff4d4f !important;
}
</style>
